package com.cwm.common.message;

import com.cwm.common.Enums.ResultEnum;
import com.cwm.common.utils.MessageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

/**
 * Message Properties
 *
 * @author Bill
 * @version 1.0
 * @since 2021-11-15
 */
@RequiredArgsConstructor
@Configuration
@PropertySource(value = "classpath:message.properties", encoding = "UTF-8")
public class MessageProperties {

    private final Environment env;

    private String getMessageTemplate(ResultEnum ResultEnum) {
        return env.getProperty(ResultEnum.getMessageKey());
    }

    public String getMessage(ResultEnum ResultEnum) {
        String messageTemplate = getMessageTemplate(ResultEnum);
        if (messageTemplate.contains("{{message}}")) {
            return MessageUtil.getMessage(messageTemplate, "");
        }
        return messageTemplate;
    }

    public String getMessage(ResultEnum ResultEnum, String... parameters) {
        String messageTemplate = getMessageTemplate(ResultEnum);
        int indexColon = messageTemplate.indexOf(":");
        int indexMessage = messageTemplate.indexOf("{{message}}");
        if (indexColon + 2 != indexMessage) {
            parameters[0] = ": " + parameters[0];
        }
        return MessageUtil.getMessage(messageTemplate, parameters);
    }

}
